#!/usr/bin/env bash

# -e : Exit immediately if a command exits with a non-zero status.
# -u : Treat unset variables as an error when substituting.
# -o pipefail : A pipeline fails if any command in the pipeline fails.
set -euo pipefail

# Define color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[0;37m'
GRAY='\033[0;90m'
BOLD='\033[1m'
UNBOLD='\033[22m'
NC='\033[0m' # No Color

SCRIPT_DIR="$(cd "$(dirname $(realpath ${BASH_SOURCE[0]}))"; pwd)"
pushd "${SCRIPT_DIR}" > /dev/null

if [[ -n "${WSL_DISTRO_NAME}" ]]; then
    TARGET=$(/mnt/c/Windows/System32/HOSTNAME.exe | tr -d '[:cntrl:]' | tr '[:upper:]' '[:lower:]')
else
    # -s : short
    TARGET=$(hostname | tr '[:upper:]' '[:lower:]')
fi

TARGET=${TARGET%".lan"} # remove suffix if exists

OS=$(uname -s)
case $OS in
    (Linux)
        if [[ -n "${WSL_DISTRO_NAME}" ]]; then
            TARGET=${TARGET%"-wsl"} # remove suffix if exists
            TARGET=${TARGET#"wsl-"} # remove prefix if exists
            TARGET="wsl-${TARGET}"
            echo -e "${CYAN}🔍 WSL target: \"$TARGET\"${NC}"
        else
            echo -e "${CYAN}🔍 Linux target: \"$TARGET\"${NC}"
        fi
        ;;
    (MINGW64_NT-*)
        echo -e "${CYAN}🔍 msys2 target: \"$TARGET\"${NC}"
        ;;
    (Darwin)
        echo -e "${CYAN}🔍 Mac target: \"$TARGET\"${NC}"
        ;;
    (*)
        echo -e "${RED}⚠️ Unknown \$(uname -s): ${BOLD}$OS${UNBOLD}${NC}"
        exit 1
        ;;
esac

function safe_ln() {
    local tgt="$1"
    local lnk="$2"

    if [[ -L "$lnk" ]]; then
        local existing="$(readlink "$lnk")"
        if [[ "$existing" == "$tgt" ]]; then
            echo -e "${GRAY}🟢 ${BOLD}$lnk${UNBOLD} already points to ${BOLD}$tgt${UNBOLD}${NC}"
            return 0
        fi
        echo -e "${RED}⚠️ ${BOLD}$lnk${UNBOLD} exists, but points to ${BOLD}$existing${UNBOLD}${NC}"
        return 1
    elif [[ -e "$lnk" ]]; then
        echo -e "${RED}⚠️ ${BOLD}$lnk${UNBOLD} exists${NC}"
        return 1
    fi

    local OS=$(uname -s)
    case $OS in
        (Linux|MINGW64_NT-*)
            # -s : symlink
            # -T --no-target-directory : always treat LINK as final file
            # -f : force, unlink if already exists
            ln -sTf "$tgt" "$lnk"
            ;;
        (Darwin)
            # -s : symlink
            # -h : do NOT follow symlink
            # -f : force, unlink if already exists
            ln -shf "$tgt" "$lnk"
            ;;
        (*)
            echo -e "${RED}⚠️ Unknown \$(uname -s): ${BOLD}$OS${UNBOLD}${NC}"
            exit 1
            ;;
    esac
}

safe_ln "$TARGET" "current"

mkdir -p "$HOME/.config"
safe_ln "$PWD/$TARGET" "$HOME/.config/shell"

popd > /dev/null
